package hy;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Demo1 {
    Jedis j = new Jedis("192.168.188.100",6379);

    @Test
    public void t1(){
        j.set("address","南京");
        System.out.println(j.get("address"));
        j.incr("num");
        System.out.println(j.get("num"));
        Set<String> keys = j.keys("*");
        for (String key : keys) {
            System.out.println(key+":"+j.get(key));
        }
        Map<String ,String> m = new HashMap<>();
        m.put("u1","a1");
        m.put("u2","a2");
        j.hmset("users",m);
        System.out.println(j.hgetAll("users"));
    }

    @Test
    public void transac()throws Exception{
        j.set("money","960");
        j.set("debt","40");
        int consume=10;
        j.watch("money");

        Thread.sleep(10000);
        int money = Integer.parseInt(j.get("money"));
        if(money<consume){
            j.unwatch();
            System.out.println("你信用卡额度不够");
            return;
        }

        System.out.println("----------开事务----------");
        Transaction t = j.multi();
        t.incrBy("debt",consume);
        t.decrBy("money",consume);
        List<Object> list = t.exec();
        if(list==null){
            System.out.println("事务失败，稍后再试");
            j.unwatch();
        }
        System.out.println("事务结束后，money为："+j.get("money")+",欠账："+j.get("debt"));
    }

    @Test
    public void ms(){
        Jedis m = new Jedis("192.168.188.100",6379);
        Jedis s = new Jedis("192.168.188.100",6380);
        //s.slaveof()
        m.set("driver","com.mysql.jdbc");
        System.out.println(s.get("driver"));
    }
}
